resetBlotterEnvironment <- function() {
  .instrument <<- new.env()
  .blotter <<- new.env()
}

openBlotterEnvironment <- function(portfoliostring, accountstring, symbols=NULL, initDate, 
                                   currency="USD", reset=FALSE, initEq=0) {
  initIt <- function() {
    currency(currency)
    initPortf(name=portfoliostring, symbols=symbols, initDate=initDate, currency=currency)
    initAcct(name=accountstring, portfolio=portfoliostring, initEq=initEq, currency=currency)
  }
  # load package if not in session yet
  if('package:blotter' %in% search() || require('blotter',quietly=TRUE)) {}
  if (reset==TRUE) {
    # remove blotter environment
    resetBlotterEnvironment()
  }
  if (suppressMessages(!is.portfolio(portfoliostring))) {
    initIt()
  } else if (reset==TRUE) {
    initIt()
  } else if (reset==FALSE) {
    stop ("Portfolio already exists and reset is FALSE, thus can't reset")
  }
}

insertPositionIntoBlotter <- function(portfoliostring, symbols, currency="USD", type="stock") {
  for (symbol in symbols) {
    if (type=="stock") {
      stock(symbol, currency=currency, multiplier=1)
    } else if (type=="future") {
      future(symbol, currency=currency, multiplier=1)
    }
    addPortfInstr(portfoliostring, symbol)
  }
}

OLDF2sortedDF <- function(OLDF) {
  dimOLDF <- dim(OLDF)
  sortedDF <- as.data.frame(matrix(nrow=dimOLDF[1]*2, ncol=4))
  colnames(sortedDF)=c("date", "direction", "price", "id")
  j <- 1
  for (i in 1:dimOLDF[1]) {
    posOpenDate <- as.Date(rownames(OLDF)[i])
    posCloseDate <- posOpenDate + OLDF[i,"days"]
    posOpenPrice <- OLDF[i,"openprice"]
    posClosePrice <- OLDF[i,"closeprice"]
    if (OLDF[i,"long"] > 0) {
      dirfactor = 1
    } else if (OLDF[i,"short"] > 0) {
      dirfactor = -1
    } else {
      stop ("position neither long nor short")
    }
    sortedDF[j,"date"] <- posOpenDate
    sortedDF[j,"direction"] <- dirfactor
    sortedDF[j,"price"] <- posOpenPrice
    sortedDF[j,"id"] <- i
    j <- j+1
    sortedDF[j,"date"] <- posCloseDate
    sortedDF[j,"direction"] <- dirfactor * (-1)
    sortedDF[j,"price"] <- posClosePrice
    sortedDF[j,"id"] <- i
    j <- j+1
  }
  # sort by date ascending
  retDF <- sortedDF[with(sortedDF, order(date, id)), ]
  return(retDF)
}


insertTransactionsIntoBlotter <- function(portfoliostring, accountstring, symbol, OLDF, TxnSize=5000, TxnFees=0) {  
  # Orders need to be sorted since blotter can't handle unordered transactions
  OrderDF <- OLDF2sortedDF(OLDF)
  dimOrderDF <- dim(OrderDF)
  TxnQty <- vector(mode="integer", length=dimOrderDF[1]/2)
  # loop through every line
  for (i in 1:dimOrderDF[1]) {
    if (TxnQty[OrderDF[i,"id"]] == 0) {
      # calculate TxnQty for this ID
      TxnQty[OrderDF[i,"id"]] = ceiling(TxnSize/OrderDF[i,"price"]) 
    }
    # add position
    addTxn(portfoliostring, Symbol=symbol, 
           TxnDate=as.Date(OrderDF[i,"date"], origin = "1970-01-01"), 
           TxnQty=(TxnQty[OrderDF[i,"id"]] * OrderDF[i,"direction"]), 
           TxnPrice=OrderDF[i,"price"], TxnFees=TxnFees)
  }
  # update portfolio
  updatePortf(portfoliostring)
  updateAcct(accountstring)
  updateEndEq(accountstring)
  chart.Posn(portfoliostring, Symbol=symbol)
}

